<template>
  <!-- 搜索框组件 -->
  <div id="headerBox">
    <header class="header">
      <div class="loginBox" v-if="!hasLogin" style="margin-right: 30px">
        <el-link
          class="iconfont icon-qunfengyonghu"
          type="info"
          plain
          :underline="false"
          @click.native="handleLoginClick"
        ></el-link>
      </div>
      <div class="loginOutBox" v-else style="margin-right: 30px">
        <span style="margin-right: 30px">欢迎, {{ userInfo.username }}</span>
        <el-link
          type="primary"
          plain
          :underline="false"
          @click.native="handleLoginOut"
          >退出登录<i class="el-icon-back el-icon--right"></i>
        </el-link>
      </div>
    </header>
    <el-dialog
      :close-on-click-modal="false"
      title="登录/注册"
      :visible.sync="dialogVisible"
      width="30%"
      :before-close="handleBeforeClose"
    >
      <!-- 登录表单 -->
      <el-form
        :rules="loginFormRules"
        ref="loginForm"
        label-width="80px"
        :model="loginForm"
        v-show="isLoginState"
      >
        <el-form-item label="用户名" prop="userName">
          <el-input v-model="loginForm.userName"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input
            v-model="loginForm.password"
            show-password
            @keyup.enter.native="handleLogin"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button @click="handleLogin" type="primary" style="width: 100%"
            >登录</el-button
          >
        </el-form-item>
      </el-form>
      <!-- 注册表单 -->
      <el-form
        :rules="registerFormRules"
        ref="registerForm"
        label-width="80px"
        :model="registerForm"
        v-show="!isLoginState"
      >
        <el-form-item label="用户名" prop="userName">
          <el-input v-model="registerForm.userName"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="registerForm.password" show-password></el-input>
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPass">
          <el-input
            v-model="registerForm.confirmPass"
            show-password
            @keyup.enter.native="handleRegister"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button @click="handleRegister" type="primary" style="width: 100%"
            >注册</el-button
          >
        </el-form-item>
      </el-form>
      <div class="change-login-link">
        <el-link
          type="primary"
          v-show="isLoginState"
          @click="setLoginState(false)"
          >立即注册</el-link
        >
        <el-link
          type="primary"
          v-show="!isLoginState"
          @click="setLoginState(true)"
          >返回登录</el-link
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
import md5Crypto from "@/utils/crypto.js";
import { loginApi, registerApi } from "@/api/index.js";
import { setToken, removeToken } from "@/utils/token.js";
export default {
  name: "HeaderBox",
  props: {
    // 用户是否登录
    hasLogin: {
      type: Boolean,
      required: true,
      default: false,
    },
  },
  created() {
    if (this.hasLogin) {
      this.userInfo = JSON.parse(sessionStorage.getItem("userInfo"));
    }
  },
  data() {
    /** 注册表单校验密码 */
    const validatePass = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入密码"));
      } else {
        if (this.registerForm.confirmPass !== "") {
          this.$refs.registerForm.validateField("confirmPass");
        }
        callback();
      }
    };
    /** 注册表单校验确认密码 */
    const validatePass2 = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请再次输入密码"));
      } else if (value !== this.registerForm.password) {
        callback(new Error("两次输入密码不一致!"));
      } else {
        callback();
      }
    };
    return {
      // 用户信息
      userInfo: {},
      // 登录对话框是否显示
      dialogVisible: false,
      // 登录表单
      loginForm: {
        userName: "",
        password: "",
      },
      // 登录表单验证规则
      loginFormRules: {
        userName: [
          { required: true, message: "请输入用户名", trigger: "blur" },
        ],
        password: [{ required: true, message: "请输入密码", trigger: "blur" }],
      },
      // 注册表单
      registerForm: {
        userName: "",
        password: "",
        confirmPass: "",
      },
      // 注册表单验证规则
      registerFormRules: {
        userName: [
          { required: true, message: "请输入用户名", trigger: "blur" },
        ],
        password: [
          { validator: validatePass, trigger: "blur" },
          { required: true, message: "请输入密码", trigger: "blur" },
        ],
        confirmPass: [
          { validator: validatePass2, trigger: "blur" },
          { required: true, message: "请再次输入密码", trigger: "blur" },
        ],
      },
      // 登录还是注册状态
      isLoginState: true,
    };
  },
  components: {
    //
  },
  methods: {
    /** 对话框关闭之前触发动作 */
    handleBeforeClose(done) {
      this.resetForm();
      done();
    },
    /** 重置表单的数据 */
    resetForm() {
      this.$refs.loginForm.resetFields();
      this.$refs.registerForm.resetFields();
    },
    /** 处理点击登录/注册按钮 */
    handleLoginClick() {
      this.dialogVisible = true;
    },
    /** 设置显示登录表单还是注册表单 */
    setLoginState(loginState) {
      this.isLoginState = loginState;
    },
    /** 校验登录/注册表单的数据格式 */
    verifyFormData(formEl) {
      let isValid = true;
      formEl.validate((valid) => {
        isValid = valid;
      });
      return isValid;
    },
    /** 点击登录按钮 */
    handleLogin() {
      if (!this.verifyFormData(this.$refs.loginForm)) {
        this.$message.error("请完善表单数据");
        return;
      }
      const data = {
        username: this.loginForm.userName,
        password: md5Crypto(this.loginForm.password),
      };
      this.sendLoginRequest(data);
    },
    /** 发送登录请求 */
    sendLoginRequest(data) {
      loginApi(data).then((res) => {
        if (res.code === 200) {
          this.$message.success("登录成功");
          this.dialogVisible = false;
          this.resetForm();
          const { token } = res.result;
          setToken(token);
          this.userInfo = res.result;
          sessionStorage.setItem("userInfo", JSON.stringify(this.userInfo));
          this.$emit("loginSuccess");
        }
      });
    },
    /** 点击注册按钮 */
    handleRegister() {
      if (!this.verifyFormData(this.$refs.registerForm)) {
        this.$message.error("请完善表单数据");
        return;
      }
      const data = {
        username: this.registerForm.userName,
        password: md5Crypto(this.registerForm.password),
        phone: "18000000000",
      };
      console.log(data);
      registerApi(data).then((res) => {
        if (res.code === 200) {
          // this.$message.success('注册成功')
          const loginData = {
            username: data.username,
            password: data.password,
          };
          this.sendLoginRequest(loginData);
        }
      });
    },
    /** 点击退出登录按钮 */
    handleLoginOut() {
      removeToken();
      sessionStorage.removeItem("userInfo");
      this.$message.success("退出登录成功");
      this.$emit("loginOut");
    },
  },
};
</script>

<style lang="less" scoped>
#headerBox {
  // 导航栏
  .header {
    display: flex;
    justify-content: right;
    padding: 10px;
  }
  ::v-deep .change-login-link {
    display: flex;
    justify-content: flex-end;
  }
}
</style>
